var express = require('express');
var path = require('path');
var domain = require('domain');
//var bodyParser = require("body-parser");
var utils = require('./utils/utils');
var bizService = require('./utils/bizService');

global.emoticonCache={};

var app = express();

// parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({ extended: false,limit : "5000kb" }))
 
// parse application/json
//app.use(bodyParser.json({limit : "50kb"}))


app.use('/emo/imgGen',function(req, res){

	
	validReplyNoResponse(req, res,function(key,request,reqId){


		var id = req.query.id;
		var params={} 	
		
		var emo = null;
		
		
		if(id){
			var ind = global.emoticonCache.emoPkey[id];
			if(ind >=0){
				emo = global.emoticonCache.emoticons[ind]
				
				if(!emo) {responseError(res,'') ;return}	
				params.fileName =  emo.fileName

				params.x = emo.x;
				params.y = emo.y;
				params.fontSize = emo.fontSize;
				params.gif = emo.gif;
				if(emo.wordWidth)params.wordWidth = emo.wordWidth;
				if(emo.lineLimit)params.lineLimit = emo.lineLimit;
				params.width = emo.width;
				params.height = emo.height;

			}else{
				responseError(res,'');
				return
			}
		}else{
			responseError(res,'');
			return
		}
		
	
		if(req.query.font) params.font = req.query.font;      // 字体库文件名
		params.msg = req.query.msg;          //消息主体
		if(req.query.color) params.color = req.query.color;      //字体颜色

	
		if(!params.fileName || !params.msg ) {responseError(res,'');return}	
	
		var arr = params.msg.replace(/[\ |\~|\`|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g,"");
	
		if(arr.length < 1)  {responseError(res,'');return}
		
		if(!params.font && emo.font) params.font= emo.font
		if(!params.color && emo.color) params.color= emo.color
		
		params.msg = encodeURI(params.msg)

		var option={}
		option.hostname= global.config.cmdHost
		option.path='/imgGen?' + utils.paramFormate(params)
		option.port=global.config.cmdPort
		
		
		utils.request(option,function(answer){
		
			if(answer && answer.length >0){
				var result=JSON.parse(answer)
				var data={}
			
				if(result.success){
					data.time=new Date().getTime();
					data.fileName= global.config.tmpPath +  result.fileName
					responseData(res,utils.desEncrypt(JSON.stringify(data),key), reqId)
					return 
				}	
				responseError(res,result.error,result.code)
				return ;
			}			
			responseError(res,'生成错误','301')
			return ;
			
			
			
		})
	}) 
	
});

app.get('/', function (req, res) {		 
		   res.send('Hi...');
		   
})
//init,cats,hotTag
app.get('/emo/init', function (req, res) {	
	var map={}
	map.hotCat=global.emoticonCache.hotCat
	map.hotDicCat=global.emoticonCache.hotDicCat
	
	map.hotTag=global.emoticonCache.param.emoTag
	map.hotDicTag=global.emoticonCache.param.dicTag
	map.emoPlace=global.emoticonCache.param.emoPlace
	map.dicPlace=global.emoticonCache.param.dicPlace
	
	map.emoFonts=global.emoticonCache.fonts
	map.emoColors=global.emoticonCache.colors
	
	
	map.emoCats=global.emoticonCache.emoCats
	
	map.dicCats=global.emoticonCache.dictumCats
	if(!utils.requestValid(req,global.emoticonCache.appKeys)){
		map.protocol='c55e7a3de6f8e781fbb3662cdbbb4d1f770e94d5635e0efe6cae8e2557fc22d9d72e028b1c06fbb9'
		map.token='274441d410e217684be317274a320d44ad3f903435b9c85915cdbd464aed4a7e'
		responseError(res,map)
		return;
	}	 
	var appkey =  utils.getAppKey(req,global.emoticonCache.appKeys)
	map.protocol=utils.desEncrypt(JSON.stringify(appkey.shadowKeys),appkey.hardKey)
	map.token=utils.desEncrypt(JSON.stringify(appkey.softKeys),appkey.hardKey)
	responseData(res,map)	
		   
})


//feeds
app.get('/emo/emoFeed', function (req, res) {	

	validReply(req, res,function(key,request){
			var data ={}
			data.feed = bizService.initEmoFeed(key);
			data.banner = bizService.initBanner(key);
			return utils.desEncrypt(JSON.stringify(data),key)
	}) 
})


app.get('/emo/emoCat', function (req, res) {

	validReply(req, res,function(key,request){
			var catId = req.query.catId
			return bizService.initEmoCat(key,catId)
	}) 
	  
})

app.get('/emo/catList', function (req, res) {
	
	validReply(req, res,function(key,request){
			var catId = req.query.catId
			return bizService.listByCat(key,catId,request)
	}) 
	 
})

app.get('/emo/imgDetail', function (req, res) {	  
		
	validReply(req, res,function(key,request){
		var id = req.query.id;
			if(id){
				var ind = global.emoticonCache.emoPkey[id];
				if(ind >=0){
					var emo = global.emoticonCache.emoticons[ind]
					var emoticon={}
					emoticon.fileName = global.config.imgPath + emo.fileName
					emoticon.id = id
					emoticon.text = ['叔叔，我们不约','我还是个孩子']
					return utils.desEncrypt(JSON.stringify(emoticon),key)
	
				}
			}
			return null;
	})
})


//feeds
app.get('/dic/dicFeed', function (req, res) {	

	validReply(req, res,function(key,request){
			var data ={}
			data.feed = bizService.initDictumFeed(key);
			return utils.desEncrypt(JSON.stringify(data),key)
	}) 
	
})


app.get('/dic/dicCat', function (req, res) {

	validReply(req, res,function(key,request){
		var catId = request.query.catId
		return bizService.initDicCat(key,catId)
	}) 
})

app.get('/dic/dicCatList', function (req, res) {
	
	validReply(req, res,function(key,request){
		var catId = request.query.catId
		return bizService.listDicByCat(key,catId,request)
	})   
})


app.get('/set/paperList', function (req, res) {		 
		validReply(req, res,function(key,request){
			return utils.desEncrypt(JSON.stringify(global.emoticonCache.papers),key)
	})  	   
})
app.get('/set/bubbleAvatarList', function (req, res) {		 
	validReply(req, res,function(key,request){
			return utils.desEncrypt(JSON.stringify(global.emoticonCache.bubbleAvatars),key)
	})  	   
})

app.get('/set/paperAvatarList', function (req, res) {		 
	validReply(req, res,function(key,request){
			return utils.desEncrypt(JSON.stringify(global.emoticonCache.paperAvatars),key)
	})  	   
})

app.get('/set/bubbleList', function (req, res) {		 
	validReply(req, res,function(key,request){
			return utils.desEncrypt(JSON.stringify(global.emoticonCache.bubbles),key)
	})   	   
})


app.get('/favorList', function (req, res) {		 
	responseData(res,global.emoticonCache.emoFeed)		   
})

app.get('/emo/searchEmo', function (req, res) {
	
	validReply(req, res,function(key,request){
			var page = parseInt(request.query.page);
			var size = parseInt(request.query.size);
			var keyword = req.query.keyword;
			if(!keyword || keyword.length == 0 || isNaN(page)){
				return ''
			}
			if(isNaN(size) || size>50) size = 40
			keyword = keyword.replace(/ /g,',')
			
			return bizService.listByCat(key,'c2d',request)
	}) 

})

app.use('/dic/searchDic',function (req, res) {		 
		validReply(req, res,function(key,request){
			var page = parseInt(request.query.page);
			var size = parseInt(request.query.size);
			var keyword = req.query.keyword;
			if(!keyword || keyword.length == 0 || isNaN(page)){
				return ''
			}
			if(isNaN(size) || size>20) size = 10
			keyword = keyword.replace(/ /g,',')
			
			return bizService.listDicByCat(key,'d2',request)
	}) 
		
		
});


function validReply(req, res,callBack){
	var requestValid = utils.requestValid(req,global.emoticonCache.appKeys)
	var reqId = req.query.reqId

	if(requestValid && reqId){
		var appkey =  utils.getAppKey(req,global.emoticonCache.appKeys)
		if(appkey.md5[reqId]){
			var data = callBack(appkey.md5[reqId],req)

			if(data &&  (typeof data=='string'))responseData(res,data,reqId)
			else {
				if(typeof data=='object' && data != null){
					responseError(res,data.error,data.code)
				}
				
				responseError(res,'')
			}
			return;
		}
	}	 	
	responseError(res,'')	
	
}

function validReplyNoResponse(req, res,callBack){
	var requestValid = utils.requestValid(req,global.emoticonCache.appKeys)
	var reqId = req.query.reqId

	if(requestValid && reqId){
		var appkey =  utils.getAppKey(req,global.emoticonCache.appKeys)
		if(appkey.md5[reqId]){
			callBack(appkey.md5[reqId],req,reqId)
			return
		}
	}	 	
	responseError(res,'')	
	
}

function responseData(res,data,reqId){
	res.writeHead(200, { "Content-Type": "application/json;charset=UTF-8" });
	var map={}
	map.code=200
	map.message="success"
	map.data = data;
	if(reqId) map.reqId=reqId
	res.end(JSON.stringify(map));
}

function responseError(res,data,code){
	res.writeHead(200, { "Content-Type": "application/json;charset=UTF-8" });
	var map={}
	map.code=201
	
	if(code){
		map.code=code
		map.message=data
	}else{
		map.message="success"
		map.data = data;
	}
	res.end(JSON.stringify(map));
}





app.use(function (req,res, next) {
			  var d = domain.create();
			  //domain
			  d.on('error', function (err) {	
			    console.log(err);		    		

				if(!res.headersSent){

			    res.statusCode = 500;
			    res.json({sucess:false, messag: ''});
			  }
			    d.dispose();
			  });
			  
			  d.add(req);
			  d.add(res);
			  d.run(next);
});



process.on('uncaughtException', function (err) {
			    console.log(new Date() + err.stack);
});
module.exports = app;
